package com.lagou.email.lagouemail.controller;

import com.lagou.email.lagouemail.service.LagouAuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lagou.email.lagouemail.service.MailService;

import javax.mail.MessagingException;
import java.util.Random;

@RestController
public class EmailController {

    @Autowired
    private MailService mailService;

    @Autowired
    private LagouAuthCodeService lagouAuthCodeService;

    @RequestMapping("/sendEmail")
    public String email(String sendUser){
        String code=randomCode();
        String message="success";
        try {
            mailService.sendHtmlMail(sendUser,"vrifycode",code);
        } catch (MessagingException e) {
            e.printStackTrace();
            message=e.getMessage();
            return message;
        }
        lagouAuthCodeService.insertCode(sendUser,code);
        return message;
    }



    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }


    @RequestMapping("/verifyCode")
    public String verifyCode(String sendUser,String verifyCode){

         boolean b = lagouAuthCodeService.verifyCOde(sendUser, verifyCode);
         if (b){
             return "success";
         }
        return "failed";
    }

}
